package com.zjl.spring.第09章_数据校验Validation;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * ClassName: ValidatorBean
 * Package: com.zjl.spring.第09章_数据校验Validation
 * Description:
 *
 * @Author 张蛟龙
 * @Create 2024/7/21 17:34
 * @Version 1.0
 */
public class ValidatorBeanValidator implements Validator {

    @Override//supports方法用来表示此校验用在哪个类型上,
    public boolean supports(Class<?> clazz) {
        return clazz.equals(ValidatorBean.class);
    }

    @Override//校验规则
    public void validate(Object target, Errors errors) {
        //name 不能为空
        ValidationUtils.rejectIfEmpty(
                errors,
                "name",
                "name.Error",
                "name不能为空");

        //age >=0   <=200
        if(target instanceof ValidatorBean vb){
            if(vb.getAge()<0){
                errors.rejectValue("age","age.small"," age < 0");
            } else if (vb.getAge() > 200) {
                errors.rejectValue("age","age.large"," age > 200");
            }
        }
    }

    @Override
    public Errors validateObject(Object target) {
        return Validator.super.validateObject(target);
    }
}
